import time
import socket
import datetime


# format timestamp to date
def date(format_str=None, timestamp=None):
    if format_str is None:
        format_str = '%Y-%m-%d %H:%M:%S'
    if timestamp is None:
        timestamp = round(time.time())
    date_str = time.strftime(format_str, time.localtime(timestamp))
    return date_str


# date to timestamp
# demo date_to_time('2018-12-09 12:30:21')
def date_to_time(date_str):
    # date convert to array
    time_array = time.strptime(date_str, "%Y-%m-%d %H:%M:%S")
    timestamp = round(time.mktime(time_array))
    return timestamp


def calculate_date(days=0, format_str='%Y-%m-%d'):
    now_time = datetime.datetime.now()
    calculate = now_time + datetime.timedelta(days=days)
    return calculate.strftime(format_str)


def get_self_ip():
    """
    获取本机ip地址
    :return: ip
    """
    s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    try:
        s.connect(('8.8.8.8', 80))
        ip = s.getsockname()[0]
    finally:
        s.close()
    return ip


if '__main__' == __name__:
    print(date('%Y%m%d'))
    print(date('%Y-%m-%d', time.time() + 30 * 24 * 3600))
    print(date('%Y-%m-%d %H:%M:%S', 1))
    print(date_to_time('2018-12-09 12:30:21'))
    print(calculate_date(-2, '%Y-%m-%d %H:%M:%S'))
    print(get_self_ip())
